<?php if(!defined('SPRITCH')) { exit(); }

// Spritch - An opensource PHP5 web framework

// Author: Luca Degasperi
// Licence: GNU GPL
// Site: http://www.spritch.org/

// Class: Router
// Summary: This class routes to the required controller
// Since: 0.9.1

final class router extends spritch
{	
	public function __construct()
	{
		$this->profiler->log('router class started');
	}
	
	private function is_protected($object,$method)
	{
		if(method_exists($object,$method))
		{
			$methods = get_class_methods($object);
			return !in_array($method,$methods);
		}
		return false;
	}

	public function route()
	{		
		$root = $this->uri->root();
		if($root != '')
			$root .= DS;
		$page = $this->uri->controller();
		$object = get($root.$page.'.controller');
		if(!is_null($object))
		{
			$action = $this->uri->action();
			$args = $this->uri->args();
			$this->profiler->log($page.' controller loaded');
			if(!$this->is_protected($object,$action))
				call_user_func_array(array($object,$action),$args);
			else
				$object->__call($action,$args);					
		}
		else
		{
			if($page != '404')
				$this->profiler->warning('controller '.$page.' not found');
			$this->profiler->log('404 controller loaded');
			$this->notfound();				
		}
	}
	
	public function notfound()
	{
		if(file_exists(CONTROLLERS.DS.'notfound'.EXT))
			get('notfound.controller');
		else
		{
			$this->output->direct();
			$this->output->message = "<h2>404</h2><p>Page not Found</p>";
		}
	}
	
	public function current_page()
	{
		
	}
}
?>